package cn.liuyi.weiyi;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import cn.edu.pku.tools.SharedPreferencesHelper;
import cn.edu.pku.tools.YJRHttpClient;
import cn.liuyi.weiyi.adapter.AddDoctorAdapter;
import cn.liuyi.weiyi.adapter.FilterCategoryAdapter;
import cn.liuyi.weiyi.adapter.FilterDetailAdapter;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

public class AddDoctorActivity extends SherlockActivity implements OnClickListener{

	LayoutInflater inflater;
	ActionBar actionBar;
	View title_bar;
	Context context;
	String response;
	JSONObject jsonInfo, doctor;
	public static JSONArray doctors;
	SharedPreferencesHelper spHelper;
	PullToRefreshListView listView;
	int index = 0;
	ListView doctor_lv,filter_category_lv, filter_detail_lv;
	TextView rank_tv,filter_tv;
	private PopupWindow rank_popup, filter_popup;
	View rank_popup_view, filter_popup_view, parent;
	TextView cancel_tv, select_rank_tv, clear_tv, select_filter_tv;
	String[] filter_category = new String[]{"省市","医院","一级科室","科室","职称","推荐"};
	AddDoctorAdapter myAddDoctorAdapter;
	DisplayImageOptions options;
	String order = "default";
	RadioGroup rank_rg;
	int from;
	String province = null,city = null, hospital = null, section = null, title = null,recommend = null,words = null;
	protected ImageLoader imageLoader = ImageLoader.getInstance();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_doctor);
		inflater = this.getLayoutInflater();
		actionBar = getSupportActionBar();
		context = this;
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.me_jobinfo)
		.showImageForEmptyUri(R.drawable.me_appointment)
		.showImageOnFail(R.drawable.head)
		.cacheInMemory(true)
		.cacheOnDisc(true)
		.considerExifParams(true)
		.displayer(new RoundedBitmapDisplayer(100))//是否设置为圆角，弧度为多少  
		.bitmapConfig(Bitmap.Config.RGB_565)
		.build();
		doctors = new JSONArray();
		myAddDoctorAdapter = new AddDoctorAdapter(context,imageLoader, options);
		initPopup();
		this.spHelper = new SharedPreferencesHelper(this.context);
		initTitleBar();
		
		initComponent();
		
		
		
		initEventListener();
		
		
		getDoctors(index);
		
	
	}
	
	/**
	 * 
	 */
	private void initPopup() {
		rank_popup_view = inflater.inflate(R.layout.rank_popup_view, null);
		 /**初始化PopupWindow*/  
        rank_popup = new PopupWindow(rank_popup_view,  
                ViewGroup.LayoutParams.MATCH_PARENT,  
                ViewGroup.LayoutParams.WRAP_CONTENT);  
        rank_popup.setFocusable(true);// 取得焦点  
        rank_popup.setBackgroundDrawable(new BitmapDrawable());  
        /**设置PopupWindow弹出和退出时候的动画效果*/  
        rank_popup.setAnimationStyle(R.style.rank_animation);
        
        
        filter_popup_view = inflater.inflate(R.layout.filter_popup_view, null);
		 /**初始化PopupWindow*/  
        filter_popup = new PopupWindow(filter_popup_view,  
               ViewGroup.LayoutParams.MATCH_PARENT,  
               ViewGroup.LayoutParams.WRAP_CONTENT);  
        filter_popup.setFocusable(true);// 取得焦点  
        filter_popup.setBackgroundDrawable(new BitmapDrawable());  
       /**设置PopupWindow弹出和退出时候的动画效果*/  
        filter_popup.setAnimationStyle(R.style.rank_animation);
		
	}

	private void initTitleBar(){
		ActionBar.LayoutParams lp = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,ActionBar.LayoutParams.WRAP_CONTENT,Gravity.CENTER);
		title_bar = inflater.inflate(R.layout.add_doctor_action_bar, null);
		
		actionBar.setCustomView(title_bar,lp);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);
	}
	private void initComponent(){
		listView = (PullToRefreshListView) findViewById(R.id.doctor_lv);
		listView.setMode(Mode.PULL_FROM_END);
		doctor_lv = listView.getRefreshableView();
		
		
		rank_tv = (TextView) findViewById(R.id.rank_tv);
		filter_tv = (TextView) findViewById(R.id.filter_tv);
		
		rank_tv.setOnClickListener(this);
		filter_tv.setOnClickListener(this);
		
		parent = findViewById(R.id.main);
		
		filter_category_lv = (ListView) filter_popup_view.findViewById(R.id.filter_category_lv);
		filter_detail_lv = (ListView) filter_popup_view.findViewById(R.id.filter_detail_lv);
		
		filter_category_lv.setAdapter(new FilterCategoryAdapter(context));
		filter_detail_lv.setAdapter(new FilterDetailAdapter(context));
		
		doctor_lv.setAdapter(myAddDoctorAdapter);
		
		cancel_tv = (TextView) rank_popup_view.findViewById(R.id.cancel_tv);
		select_rank_tv = (TextView) rank_popup_view.findViewById(R.id.select_rank_tv);
		rank_rg = (RadioGroup) rank_popup_view.findViewById(R.id.order_rg);
		clear_tv = (TextView) filter_popup_view.findViewById(R.id.clear_tv);
		select_filter_tv = (TextView) filter_popup_view.findViewById(R.id.select_filter_tv);

	}
	
	private void initEventListener(){
		
		cancel_tv.setOnClickListener(this);
		select_rank_tv.setOnClickListener(this);
		clear_tv.setOnClickListener(this);
		select_filter_tv.setOnClickListener(this);
		rank_rg.setOnCheckedChangeListener(new OnCheckedChangeListener(){

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				int rb_id = group.getCheckedRadioButtonId();
				switch(rb_id){
				case R.id.money_rank_rb:
					order = "funding";
					break;
				case R.id.start_rank_rb:
					order = "hand";
					break;
				default:
					break;
				}
				
			}
			
		});
		doctor_lv.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(AddDoctorActivity.this, DoctorPageActivity.class);
				try {
					doctor = doctors.getJSONObject(position-1);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				intent.putExtra("doctor", doctor.toString());
				startActivity(intent);
				
			}
			
		});
		
		listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				if(index==0){
					Toast.makeText(context, "已经是第一页", Toast.LENGTH_SHORT).show();
					listView.onRefreshComplete();
					return;
				}
				String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

				// Update the LastUpdatedLabel
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

				// Do work to refresh the list here.
				refreshDoctor(0);
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

				// Update the LastUpdatedLabel
				
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

				// Do work to refresh the list here.
				refreshDoctor(1);
				
				
			}
			
		});

		
	}

	@SuppressLint("NewApi")
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.rank_tv:
			openPopWindow();
			break;
		case R.id.filter_tv:
			openFilterPopWindow();
			break;
		case R.id.cancel_tv:
			rank_popup.dismiss();
			break;
		case R.id.clear_tv:
			filter_popup.dismiss();
			break;
		case R.id.select_rank_tv:
			break;
		case R.id.select_filter_tv:
			break;
		default:
				break;
		}
		
	}
	
	private void getDoctors(int from, String num, String province, String city, String hospital, String section, String title,String recommend, String words, String order,String topSectionId){
		RequestParams params = new RequestParams(); 
		params.add("from",from+"");
        params.add("num", num);
        params.add("conditions.province", province);
        params.add("conditions.city", city);
        params.add("conditions.hospitalId", hospital);
        params.add("conditions.title", title);
        params.add("conditions.recommend", recommend);
        params.add("conditions.words", words);
        params.add("order",order);
        params.add("conditions.topSectionId", topSectionId);
		YJRHttpClient.post(context,"/patient/searchDoctors", params, new JsonHttpResponseHandler(){
			 @Override  
	            public void onSuccess(JSONObject data) {  
	             	jsonInfo = data;
	             	try {
						if(jsonInfo.getInt("result") == 1){
							YJRHttpClient.setCookie(context); 
							//Toast.makeText(context, "获取医生列表成功", Toast.LENGTH_SHORT).show();
							if(jsonInfo.getJSONArray("response").length()!=0){
								JSONArray doctors_ = jsonInfo.getJSONArray("response");
								for(int i = 0; i < doctors_.length(); i++){
									doctors.put(doctors_.getJSONObject(i));
								}
								myAddDoctorAdapter.notifyDataSetChanged();
							}
							
							
						}else{
							Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }  
			 @Override  
		     public void onFinish() {  
		         // Completed the request (either success or failure) 
				 listView.onRefreshComplete();
		     }  
		});
	}
	
	
	private void getDoctors(int from){
		RequestParams params = new RequestParams(); 
		params.add("from",from+"");
        params.add("num", "10");
		YJRHttpClient.post(context,"/patient/searchDoctors", params, new JsonHttpResponseHandler(){
			 @Override  
	            public void onSuccess(JSONObject data) {  
	             	jsonInfo = data;
	             	try {
						if(jsonInfo.getInt("result") == 1){
							YJRHttpClient.setCookie(context); 
							Toast.makeText(context, "获取医生列表成功", Toast.LENGTH_SHORT).show();
							if(jsonInfo.getJSONArray("response").length()!=0){
								JSONArray doctors_ = jsonInfo.getJSONArray("response");
								for(int i = 0; i < doctors_.length(); i++){
									doctors.put(doctors_.getJSONObject(i));
								}
								myAddDoctorAdapter.notifyDataSetChanged();
							}
							//listView.onRefreshComplete();
							
							
						}else{
							Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }  
			 @Override  
		     public void onFinish() {  
		         // Completed the request (either success or failure)  
				 listView.onRefreshComplete();
		     }  
		});
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
	      switch (requestCode) {
	      default:  
	          break;  

	      }  
	      super.onActivityResult(requestCode, resultCode, data);  
	  }  
	
	public void openPopWindow() {  
        /**设置PopupWindow弹出后的位置*/  
		rank_popup.showAtLocation(parent, Gravity.BOTTOM, 0, 0);  
    }  
	public void openFilterPopWindow() {  
        /**设置PopupWindow弹出后的位置*/  
		filter_popup.showAtLocation(parent, Gravity.BOTTOM, 0, 0);  
    }  
	
	private void refreshDoctor(int type){
		if(type==0&&index >= 1){
			index = index - 10;
		}else{
			index = index + 10;
		}
		getDoctors(index);
	}

}